package com.gupaoedu.design.observer.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2018/3/20.
 */
public class EventListener{

    private Map<Enum, Event> eventParam = new HashMap<Enum, Event>();

    public void addListener(Enum eventsType, Object target, Method callback) {
        if (eventParam.containsKey(eventsType)) {
            Event event = eventParam.get(eventsType);
            event.setTarget(target);
            event.setCallback(callback);
        } else {
            eventParam.put(eventsType, new Event(target, callback));
        }
    }

    protected void trigger(Enum call) {
        if (!eventParam.containsKey(call)) {
            return;
        }

        trigger(this.eventParam.get(call).setTrigger(call.toString()));
    }

    private void trigger(Event e) {
        e.setSource(this);
        e.setTime(System.currentTimeMillis());

        try {
            e.getCallback().invoke(e.getTarget(), e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
